﻿using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;

namespace TianlalaHSB.Views;

/// <summary>
/// Socket类TCP/IP通信客户端
/// </summary>
public partial class SocketView : Window
{
    private Socket _socket;
    
    public SocketView()
    {
        InitializeComponent();
    }

    private async void Connect_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            // 创建一个Socket
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // 连接到服务器
            _socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3001));
            MessageBox.Show("Connected to server.");

            await ReceiveDataAsync();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
    }

    private async void Send_Click(object sender, RoutedEventArgs e)
    {
        if (_socket.Connected)
        {
            // 将消息转换为字节
            var bytesToSend = Encoding.ASCII.GetBytes(txtSend.Text);

            // 发送消息
            _socket.Send(bytesToSend);
        }
        else
        {
            MessageBox.Show("Please connect to the server first.");
        }
    }

    private async void Close_Click(object sender, RoutedEventArgs e)
    {
        if (_socket.Connected)
        {
            _socket.Close();
        }
    }

    private async Task ReceiveDataAsync()
    {
        while (_socket.Connected)
        {
            try
            {
                var bytesToReceive = new byte[1024];
                var receiveTask = _socket.ReceiveAsync(bytesToReceive, SocketFlags.None);

                //超过5秒后提示出错
                if (await Task.WhenAny(receiveTask, Task.Delay(5000)) == receiveTask)
                {
                    var bytesReceived = receiveTask.Result;
                    var response = Encoding.ASCII.GetString(bytesToReceive, 0, bytesReceived);

                    //txtReceive.AppendText(response);
                    //txtReceive.AppendText(Environment.NewLine);
                }
                else
                {
                    //txtReceive.AppendText("error");
                    //txtReceive.AppendText(Environment.NewLine);
                }
            }
            catch (Exception ex)
            {
                //txtReceive.AppendText("error");
                //txtReceive.AppendText(Environment.NewLine);
            }
        }
    }
}